package com.cy.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.jboss.logging.Logger;
import org.springframework.stereotype.Service;

import com.cy.system.entity.User;
import com.cy.system.entity.UserRole;
import com.cy.system.mapper.UserMapper;
import com.cy.system.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
@Service
public class UserServiceImpl implements UserService{
	private Logger logger = Logger.getLogger(UserServiceImpl.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
	
	@Resource
	UserMapper userMapper;

	@Override
	public int editUser(User user) {
		int flag = 0;
		SimpleDateFormat sdf = new SimpleDateFormat();
		user.setUpdateDate(sdf.format(new Date()));
		if(user.getUserId()==0) {
			flag = userMapper.addUser(user);
		}else {
			flag = userMapper.updateUser(user);
		}
		
		return flag;
	}

	@Override
	public int delUserByAccountId(int accountId) {
		return userMapper.delUserByAccountId(accountId);
	}

	@Override
	public User getUserByAccountId(int accountId) {
		
		return userMapper.getUserByAccountId(accountId);
	}

	@Override
	public User getUserByUserId(int userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int setUserRoleIds(List<UserRole> userRoleList) {
		return userMapper.setUserRoleIds(userRoleList);
	}

	@Override
	public List<Integer> getUserRoleIds(int userId) {
		return userMapper.getUserRoleIds(userId);
	}

	@Override
	public List<User> getAllUser(Page page) {
		PageHelper.startPage(page.getPageNum(),page.getPageSize());
		List<User> resList = userMapper.getAllUser();
		return resList;
	}

	@Override
	public User findUserByUserName(String userName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int addUser(User user) {	
		return userMapper.addUser(user);
	}

	@Override
	public int updateUser(User user,HttpSession session) {
		String tempStr = user.getDeptName();
		int end = tempStr.indexOf("、"); 
		logger.info("==> deptId["+tempStr.substring(0,end)+"]");
		logger.info("==> deptName["+tempStr.substring(end+1)+"]");
		user.setDeptId(Integer.parseInt(tempStr.substring(0,end)));
		user.setDeptName(tempStr.substring(end+1));
		User sessionUser = (User) session.getAttribute("userSession");
		user.setUpdateBy(sessionUser.getUserName());
		user.setUpdateDate(sdf.format(new Date()));
		return userMapper.updateUser(user);
	}

	@Override
	public List<Map> getAllUserMap(Page page) {
		PageHelper.startPage(page.getPageNum(),page.getPageSize());
		List<Map> resList = userMapper.getAllUserMap();
		return resList;
	}

}
